<?php

include_once "baseChannel.php";

class Seller extends BaseChannel
{

    protected $mchid;
    protected $userKey;

    // 辅助加密参数
    protected $aesIV = 1111111111111111;
    public function __construct($options)
    {
        parent::__construct($options);
        $this->mchid =  $options['mchid'];
        $this->userKey =  $options['userKey'];
        // return
    }
    // 计算签名
    public function getSign($data)
    {
        $data = json_encode($data);
        return $this->aes_encrypt($data, $this->userKey, $this->aesIV);
    }
    function aes_encrypt($data, $key, $iv = '')
    {
        $str_padded = $data;
        if (strlen($str_padded) % 16) {
            $str_padded = str_pad($str_padded, strlen($str_padded) + 16 - strlen($str_padded) % 16, "\0");
        }
        $data = openssl_encrypt($str_padded, 'AES-128-CBC', $key, OPENSSL_NO_PADDING, $iv);
        return base64_encode($data);
    }
    public function queryBalance($params = [])
    {
        $data['mchid'] = $this->mchid;
        $data['time'] = time();
        $data['sign'] = md5($data['mchid'] . $data['time'] . $this->userKey);
        $return_str = $this->httpRequest($this->query_balance_url, 'POST', $data);
        $return_data = json_decode($return_str, 1);

        if ($return_data['code'] == 3) {
            return [
                'error' => 0,
                'msg' => '查询成功',
                'balance' => $return_data['data']['money'] ?? null, //余额
                'credit' => 0, //授信
                'code' => 200
            ];
        }
        return [
            'error' => 1,
            'msg' => $return_data['msg'] ?? '查询失败',
            'code' => 500
        ];
    }
    public function queryOrder($params)
    {

        $data['mchid'] = $this->mchid;
        $data['order_id'] = $params['push_order_sn'];
        $data['time'] = time();
        $data['sign'] = md5($data['mchid'] . $data['order_id'] . $data['time'] . $this->userKey);
        //        var_dump($data);
        $return_str = $this->httpRequest($this->query_order_url, 'POST', $data);
        $return_data = json_decode($return_str, 1);


        $ret = [
            'error' => 0,
            'order_status' => 2,
            'msg' => '初始化',
            'pz' => '', //凭证
            'post_data' => json_encode($data), //提交字符串
            'channel_data' => $return_str, //返回字符串
            'code' => 200
        ];
        // 成功
        if ($return_data['code'] == 3 && $return_data['data']['status'] == 3) {
            $ret['order_status'] = self::OrderSuccess;
            $ret['msg'] = '查询充值完成:' . $return_data['data']['status'];
        }
        // 失败
        if ($return_data['code'] == 3 && $return_data['data']['status'] == 2) {
            $ret['order_status'] = self::OrderFail;
            $ret['msg'] = '查询充值失败' . $return_data['data']['status'];
        }

        return $ret;
    }
    public function submitOrder($mobile, $code, $params = [])
    {
        //我们的$params['isp']值 1移动 2联通 3电信
        $isp_map = [
            1 => 3,
            2 => 1,
            3 => 2
        ];
        $post_data = [
            'ChargeAccount' => $mobile,
            'SupBuyNum' => 1,
            'ChargeValue' => $code,
            'OrderType' => 1,
            'ChargeType' => $isp_map[intval($params['isp'])],
            'Id' => $params['push_order_sn'],
        ];
        $data = [];
        $data['mchid'] = $this->mchid;
        $data['notifyurl'] = $this->callback_url;
        $sign = $this->getSign($post_data);
        $data['data'] = $sign;
        $return_str = $this->httpRequest($this->submit_order_url, 'POST', $data);

        $return_data = json_decode($return_str, 1);

        $ret = [
            'error' => -1,
            'msg' => '初始化',
            'channel_order' => $return_data['data']['trans_sn'] ?? '',
            'post_data' => json_encode($data),
            'channel_data' => $return_str,
            'code' => 200,
            'channel_order_price' => null,
            'channel_balance' => null,
        ];
        if ($return_data['code'] == 'success') {
            $ret['error'] = 0;
            $ret['msg'] = $return_data['msg'] ?? '下单成功';
        } else {
            //下单失败 1006 余额不足
            if (isset($return_data['code'])) {
                $ret['error'] = 1;
                $ret['code'] = 500;
                $ret['msg'] = $return_data['msg'] ?? '下单失败';
            }
        }

        return $ret;
    }
    public function callback($params)
    {
        $post = $params['PostData'];
        $post = str_replace(' ', '+', $post);
        $post = $this->aes_decrypt($post, $this->userKey, $this->aesIV);
        $post = strstr($post, '}', true) . "}";
        $post = json_decode($post, true);

        $this->callback_params = $post;

        $this->channel_order_sn = '';
        $this->push_order_sn = $post['OrderNo'];
        //返回参数
        $res = $this->initCallBackParam();

        //订单状态
        $order_status = $post['Status'];
        $msg = $post['Description'];
        //凭证
        $pz = '';

        if ($order_status == 3) {
            $res['order_status'] = self::OrderSuccess;
            $res['msg'] = $post['Description'] ?? '充值完成';
        }
        if ($order_status == 2) {
            $res['order_status'] = self::OrderFail;
            $res['msg'] = $post['Description'] ?? '充值失败';
        }

        return $res;
    }
    public function aes_decrypt($data, $key, $iv = '')
    {
        $encrypted = base64_decode($data);
        return openssl_decrypt($encrypted, 'AES-128-CBC', $key, OPENSSL_NO_PADDING, $iv);
    }
}
